﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EBookStore.Users
{
    class UsersManager
    {
        private static UsersManager _instance = null;
        private static object _syncObj = new object();

        List<User> _users;


        /// <summary>
        /// Manager instance
        /// </summary>
        public static UsersManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObj)
                    {
                        if (_instance == null)
                        {
                            _instance = new UsersManager();
                        }
                    }
                }
                return _instance;
            }
        }


        public List<User> Users
        {
            get { return _users; } 
        }


        /// <summary>
        /// 
        /// </summary>
        public UsersManager()
        {
            _users = new List<User>();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public User Login(string Username, string Password)
        {
            var q = (from el in Users where el.Login.Equals(Username) && el.Password.Equals(Password) select el).FirstOrDefault();
            return q;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public User FindUser(string ID)
        {
            var q = (from el in Users where el.ID.Equals(ID) select el).FirstOrDefault();
            return q;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool AddUser(User user)
        {
            if (user.ValidateData())
            {
                // TODO: Check there is not such LOGIN already

                _users.Add(user);
                return true;
            }
            return false;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Orders.Order[] GetOrders(User user)
        {
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool RemoveUser(User user)
        {

            Orders.Order[] orders = GetOrders(user);
            if (orders != null && orders.Length > 0)
                return false;
            else
            {
                _users.Remove(user);
                return true;
            }
        }

    }
}
